
var net = require('net');

var MessageSocket = require('./modules/message/MessageSocket');
var MessageParser = require('./modules/message/MessageParser');

var config  = require('./config.js') || {};


var listenPort  = config.listenPort || 5000;
var server      = net.createServer();

server.on( 'connection', function( socket ) {
    
    var msgSock = new MessageSocket(socket);

    msgSock.on( 'message', function( msgBuffer ) {
        
        var msgParsed = new MessageParser(msgBuffer).parse();


        // debug
        console.log('[MessageSocketHandler] A complete message has been take out:');
        console.log(msgBuffer);
        console.log(msgBuffer.toString());

        console.log('parsedMessage:');
        console.log( msgParsed );

        console.log('[MessageSocketHandler] End!\n');

        if(msgParsed) {

            var sizeBuffer = new Buffer(4);
            var msgParsedBuffer = new Buffer(msgParsed);
            sizeBuffer.writeUInt32BE( msgParsedBuffer.length+6, 0 );
            var outputBuffer = Buffer.concat( [new Buffer([4]), sizeBuffer, new Buffer([0]), msgParsedBuffer ] );

            socket.write(outputBuffer);
        }
        

        // var Processor = require('./modules/processor/'+msgParsed.processor+'Processor');
        // new Processor( msgParsed, socket ).run();

    });
    
});

server.listen( listenPort );